import { message } from 'antd';
import {
    resetPassword,
    checkUserEmail,
    getVerificationCode
} from '@/services/user';

export default {
    namespace: 'forgotPassword',

    state: {
        status: undefined,
        msg: ''
    },

    effects: {
        *checkUserEmail({ payload, callback }, { call, put }) {
            const response = yield call(checkUserEmail, payload);
            if (response.code === 10000) {
                yield put({
                    type: 'checkUserEmailHandle',
                    payload: {
                        ...payload,
                        ...response.data
                    }
                });
                if (callback && typeof callback === 'function') {
                    callback();
                }
            } else {
                message.error(response.msg);
            }
        },
        *resetPassword({ payload, callback }, { call, put }) {
            const response = yield call(resetPassword, payload);
            if (response.code === 10000) {
                yield put({
                    type: 'resetPasswordHandle',
                    payload: {
                        ...response.data
                    }
                });
                if (callback && typeof callback === 'function') {
                    callback();
                }
            } else if (response.code === 20011) {
                message.error('不能频繁重置密码');
            } else if (response.code === 20012) {
                message.error('旧密码不正确');
            } else if (response.code === 10201) {
                message.error('密码需包含大小写字母、数字，长度在8-20位');
            } else if (response.code === 20010) {
                message.error('验证码错误');
            } else {
                message.error(response.msg);
            }
        },
        *getVerificationCode({ payload, callback }, { call, put }) {
            const response = yield call(getVerificationCode, payload);
            if (response.code === 10000) {
                yield put({
                    type: 'getVerificationCodeHandle',
                    payload: {
                        ...response.data
                    }
                });
                if (callback && typeof callback === 'function') {
                    callback();
                }
            } else {
                message.error(response.msg);
            }
        }
    },
    reducers: {
        checkUserEmailHandle(state, { payload }) {
            return {
                ...state,
                ...payload
            };
        },
        resetPasswordHandle(state, { payload }) {
            return {
                ...state,
                ...payload
            };
        },
        getVerificationCodeHandle(state, { payload }) {
            return {
                ...state,
                ...payload
            };
        }
    }
};
